package com.ecreditpal.audio.platform.tencent;


import com.baidu.aip.util.Base64Util;
import com.ecreditpal.audio.AsrCallback;
import com.ecreditpal.audio.AsrRunner;
import com.ecreditpal.audio.model.AudioSession;
import com.ecreditpal.audio.platform.Config;
import com.ecreditpal.audio.WorkDispatcher;
import com.ecreditpal.audio.util.BaseUtil;
import com.ecreditpal.audio.util.MyHttpClient;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * 腾讯云语音识别接口
 */
@Slf4j
public class tencentDemo extends AsrRunner {
    private final static String CHARSET = "UTF-8";
    private static String SECRET_KEY = "HSaaam4IMMD0u5BAzsDQVSVREqJwkRzP";


    /**
     *
     * @param params 请求参数
     * @param method 请求方法
     * @param url 请求url
     * @return 最终加密串
     */
    public static String generateSignature(TreeMap<String, String> params, String method, String url) {
        StringBuilder sb = new StringBuilder();
        sb.append(method).append(url).append("?");
        for (String s : params.keySet()) {
            sb.append(s).append("=").append(params.get(s)).append("&");
        }
        sb.replace(sb.lastIndexOf("&"), sb.length(), "");

        return BaseUtil.sign(sb.toString(), SECRET_KEY, "HmacSHA1",CHARSET);
    }
    public static String GetVoiceStr(String imgFile)
    {//将音频文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        return Base64.encode(data);//返回Base64编码过的字节数组字符串
    }
    private static byte[] inputStreamToByte(InputStream is){
        ByteArrayOutputStream bytestream = null;
        byte[] buffer = new byte[1024];
        int ch;
        try {
            bytestream = new ByteArrayOutputStream();
            while ((ch = is.read(buffer)) != -1) {
                bytestream.write(buffer, 0, ch);
            }
            byte[] data = bytestream.toByteArray();
            return data;
        }catch (IOException e){
            log.info("[Transform Exception]Fail to transform inputStream to byte array! message : {}", e.toString());
            return null;
        } finally {
            try {
                if (bytestream != null)
                    bytestream.close();
            }catch (IOException e){
                log.info("[Stream close Exception] message : {}", e.toString());
            }

        }
    }
    public static String tencentAsr(InputStream is){
        Long time1=System.currentTimeMillis();
        String Timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
        String URL = "https://aai.tencentcloudapi.com";
        byte[] data2=inputStreamToByte(is);
        String data3=Base64Util.encode(data2);
        TreeMap<String, String> params = new TreeMap<String, String>(); // TreeMap可以自动排序
        params.put("Action", "SentenceRecognition");
        params.put("Region", "ap-guangzhou");
        params.put("Timestamp", Timestamp);
        params.put("Nonce", "64");
        params.put("SecretId","AKIDiKLITcDfYJ4jU4wjs4wwqZMRgP90wWM8");
        params.put("Version", "2018-05-22");
        params.put("ProjectId", "0");
        params.put("SubServiceType","2");
        params.put("EngSerViceType", "8k");
        params.put("SourceType", "1");
        params.put("VoiceFormat", "wav");
        params.put("UsrAudioKey", "xbxbxbx");
        params.put("Data", data3);
        params.put("DataLen", data3.length()+"");

        //生成校验码
        params.put("Signature", generateSignature(params,"POST","aai.tencentcloudapi.com/"));
        //发起post请求

        String result= MyHttpClient.post(URL, params);
        Long time2=System.currentTimeMillis();
        return result;
    }
    public static void main(String[] args) throws Exception {
        String Timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
        String data = GetVoiceStr("/Users/xuebinxu/Downloads/pp2.wav");
        String URL = "https://aai.tencentcloudapi.com";
        TreeMap<String, String> params = new TreeMap<String, String>(); // TreeMap可以自动排序
        params.put("Action", "SentenceRecognition");
        params.put("Region", "ap-guangzhou");
        params.put("Timestamp", Timestamp);
        params.put("Nonce", "6");
        params.put("SecretId","AKIDiKLITcDfYJ4jU4wjs4wwqZMRgP90wWM8");
        params.put("Version", "2018-05-22");
        params.put("ProjectId", "0");
        params.put("SubServiceType","2");
        params.put("EngSerViceType", "8k");
        params.put("SourceType", "1");
        params.put("VoiceFormat", "wav");
        params.put("UsrAudioKey", "xbxbxbx");
        params.put("Data", data);
        params.put("DataLen", data.length()+"");

        //生成校验码
        params.put("Signature", generateSignature(params,"POST","aai.tencentcloudapi.com/"));
        //发起post请求
        String result = MyHttpClient.post(URL, params);
        System.out.println("169====="+result);

    }

    @Override
    public void init(Config config) {
        log.info("[Init]初始化");
        /*this.tencentDemo2=new tencentDemo(config.getAppKey(),config.getAppSecret());*/
        log.info("初始化结束");
    }

    @Override
    public void process(byte[] data, AsrCallback asrCallback) {

    }

    public void execute(InputStream inputStream, CountDownLatch cdl) {
        Thread t = new Thread(){
            @Override
            public void run(){
                try{
                    tencentAsr(inputStream);
                    log.info("[Success] ");
                } finally {
                    cdl.countDown();
                }
            }
        };
        WorkDispatcher.getInstance().taskExecute(t);
    }

}
